const statusMap = {
  0:'初始化',  
  1:'已获取账号Local，使用LocalStorage登录',
  2:'已获取账号Local，使用LocalStorage登录失败',
  3:'已获取账号Local，使用账号密码登录',
  4:'登录成功，需要切换账号'
}
setTimeout(() => {
  window.location.reload()
}, 120000);
const checkUser = () => {
  console.log('检查人机')
  if(window.location.href.indexOf('https://www.hapag-lloyd.cn/solutions/auth/login.html') != -1 || window.location.href.indexOf('https://www.hapag-lloyd.cn/solutions/my-quotations') != -1){
    const robotDom = document.getElementById('Uiuv1')
    console.log('robotDom',robotDom)
    if(robotDom && robotDom.style.display != 'none'){
      const ipt = document.querySelector('#Uiuv1 input')
      const pms = {
        'bubbles': true, 
        'cancelable': true,
        'useCapture': false,
        'passive': false,
        'once': false,
      }
      ipt.dispatchEvent(new MouseEvent('click',pms ))
    }else {
      setTimeout(() => {
        checkUser()
      }, 2000);
    }
  }
}
const init = () => {
  const hasSelectAll = $("#accept-recommended-btn-handler")?.get(0)
  if(hasSelectAll){
    hasSelectAll.click()
  }
  setTimeout(async () => {
    const acceptCookies = document.getElementById('hal-cookieconsent-button')
    if(acceptCookies){
      acceptCookies.click()
    }
    checkUser()
    if (webError()) {
      const pluginName = await session.get('pluginName', '')
      const serverName = await session.get('serverName', '')
      const hostCode = await session.get('serverName', '')
      core.sendMsg(hostCode, hostCode+'插件[' + pluginName + ',服务器:' + serverName + ']出现人机验证或者被封禁,请前往确认');
      return;
    }
    // 页面刷新之后  await statusDiv();  一下就行了
    await statusDiv()
  
    // 检查登陆
    const isLogin = getIslogin()
    
    // 初始化
    const status = await GetAccountStatus()
    await session.set("msg",statusMap[status])
    // 登录逻辑 这里就是登录页
    if(window.location.href.indexOf('https://identity.hapag-lloyd.cn/') != -1){
      console.log('登录页')
      await setStatus(3)
      // await setAccountToSession()
      // 已获取账号Local，使用账号密码登录
      // 登录form
      // 判断是否有这种model
      const hasSelectAll = $("#accept-recommended-btn-handler")?.get(0)
      // 登录form
      const loginForm = $("#localAccountForm")?.get(0)
      // 登录页
      if(hasSelectAll && loginForm){
        hasSelectAll.click()
        // 设置账号到loginForm
        setAccount()
      }
    }else if(status == null){
      await setStatus(0)
      window.location.reload()
    }else if(status == 0){
      console.log('初始化初始化')
      await session.set("msg","初始化初始化")
      await setAccountToSession()
      const a = await getAccountFromSession()
      await setAccountToLocal(a)
    } else if(status == 4){
      await setAccountToSession()
      const a = await getAccountFromSession()
      await setAccountToLocal(a)
    }else if(isLogin && status == 1){
      console.log('已登录')
      await session.set("msg","已登录")
      // 已登录，存信息
      await saveLocalAndCookie()
    }else if(status == 1 && !isLogin) {
      // 已获取账号Local，使用LocalStorage登录失败
      await setStatus(2)
      window.location.reload()
      console.log('已获取账号Local，使用LocalStorage登录失败')
      await session.set("msg","已获取账号Local，使用LocalStorage登录失败")
    }else if(status == 2){
      console.log('准备跳转到登录页')
      await session.set("msg","准备跳转到登录页,localStorage")
      sendMsg({action: 'delCookie',domain:'.hapag-lloyd.cn'})
      localStorage.clear()
       // nav上面的 login 按钮
       const navBtn = $("#hal-navigation .hal-navigation-top-login-sign .hal-button")?.get(0)
       if(navBtn){
        // 跳转到登录页
        navBtn?.click()
      }
      const ul = $('.hal-login-box-details .hal-navigation-top-child a').get(4)
      ul?.click()
    }else if(status == 3){
      console.log('准备跳转到登录页')
      await session.set("msg","准备跳转到登录页,localStorage")
      sendMsg({action: 'delCookie',domain:'.hapag-lloyd.cn'})
      localStorage.clear()
       // nav上面的 login 按钮
       const navBtn = $("#hal-navigation .hal-navigation-top-login-sign .hal-button")?.get(0)
       if(navBtn){
         // 跳转到登录页
         navBtn.click()
       }
       const ul = $('.hal-login-box-details .hal-navigation-top-child a').get(4)
       ul.click()
    }
    clearTimer()
  }, 3000)
}

window.onload = init

const GetAccountStatus = async () => {
  const ob = await session.get('accountStatus' ,'{}')
  return JSON.parse(ob).s
}

const getIslogin = () => {
  const c = $('.hal-navigation-top-login-text .hal-navigation-top-login-text-headline')?.get(0)
  // console.log(c,'cookikiiii')
  // const token = localStorage.getItem('token')
  return c && c.innerHTML
}
const setAccountToLocal = async (ac) => {
  console.log(ac)
  if(!ac){
    return console.error('没有获取到账号信息!')
  }
  const { otherCache } = ac
  if(otherCache) {
    const obj = JSON.parse(otherCache) 
    const local = obj.localStorage
    console.log('插入local',local)
    
    for (const key in local) {
      localStorage.setItem(key, local[key])
    }
    console.log('存入本地的localStorage',window.localStorage)
    const c = obj.cookies
    console.log('插入cookies',c)

    await session.set("msg","插入cookies,localStorage")
    //设置localStorage 到 目标网站域
    // let message = {"from": "extenstion", "action": "localStorage_set", data: local};
    // window.postMessage(message, "*");

    //设置cookies 到 目标网站域
    sendMsg({action: 'setCookie', data: c})

    setTimeout(async() => {
      await setStatus(1)
      window.location.reload();
    }, 3000);
  }else{
    // 没有otherCache 直接扭转
    setTimeout(async() => {
      await setStatus(2)
      window.location.reload();
    }, 1000);
  }
}
const getAccountAndRefreshAccount = async (ac) => {
  if(!ac){
    return console.error('没有获取到账号信息!')
  }
  await setStatus(3)
  // const { apiToken, otherCache } = ac
  console.log(ac,123123)
}
const setStatus = async (s) => {
  return await session.set('accountStatus',JSON.stringify({s}))
}
const saveLocalAndCookie = async () => {
  // 登录成功刷新cookie
  sendMsg({action:"getCookie",domain:'.hapag-lloyd.cn'})
  console.log('登录成功！！！！！！！！！！！！')
  await session.set("msg","登录成功！！！！！！！！！！！！")
  const a = await getAccountFromSession()
  let local = {}
  for (const key in window.localStorage) {
    const v = localStorage.getItem(key)
    if(v){
      local[key] = v
    }
  }
  setTimeout( async () => {
    const cc = await session.get("cookies", '[]')
    console.log('获取cookies',cc)
    await session.set("msg","获取cookies")
    const apiToken = {
      'X-Token':'',
    }
    for (let i = 0; i < cc.length; i++) {
      const val = cc[i]
      if(val.name == 'auth_prod'){
        apiToken['X-Token'] = val.value
      }
    }
    const pamams = {
      ...a,
      otherCache:JSON.stringify({
        localStorage:local,
        cookies:cc,
      }),
      apiToken: JSON.stringify(apiToken),
    }
    // 更新账户
    core.updateAccount(pamams)
  }, 10000);
    // 成功以后切换账号
    // 清空
  setTimeout(() => {
    window.localStorage.clear()
    // clearCookies()
    console.log('清空local',window.localStorage)
    console.log('清空cookies',document.cookie)
  }, 17000);
  setTimeout(async () => {
    console.log('准备切换账号')
    await session.set("msg","准备切换账号")
    await setStatus(4)
    window.location.reload()
  }, 20000);
}
const setAccountToSession = async () => {
  await session.remove('accountFromServer')
  const pluginName = await session.get("pluginName", null)
  const serverName = await session.get("serverName", null)
  const hostCode = await session.get("hostCode", null)
  // HPL-TOKEN保活插件_1', 'hpl', 'zc_pc_01'
  const res = core.getAccount(pluginName, hostCode, serverName);
  console.log('当前账号====>',res)
  await session.set("msg","当前账号===>"+res?.username)
  await session.set('accountFromServer', JSON.stringify(res))
}

// 删除cookie
const  clearCookies  = () => {
  var cookies = document.cookie.split(";");
  for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i];
    var eqPos = cookie.indexOf("=");
    var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
    document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
  }
}

// 获取账号
const getAccountFromSession = async () => {
  const se = await session.get('accountFromServer','{}')
  return JSON.parse(se)
}

// 设置账号到loginForm
const setAccount = async () => {
  const account = await getAccountFromSession()
  console.log('account',account)
  if(!account || !account.username){
    await setAccountToSession()
  }
  const a = await getAccountFromSession()
  console.log(a)
  const elipt = $("#signInName").get(0)
  const pwdipt = $("#password").get(0)
  elipt.value = a.username
  pwdipt.value = a.password
  const btn = $("#localAccountForm .buttons #next").get(0)
  console.log(btn,'登录btn')
  await session.set("msg","准备点击登录btn")
  setTimeout( async () => {
    console.log('触发登录按钮')
    await session.set("msg","触发登录按钮")
    btn.click({})
    await setStatus(1)
    getLoginError(a)
  }, 10000);
}
let timer = null
const getLoginError = (errorAccount) => {
  timer = setInterval(async () => {
    const errorDiv = $('.error.pageLevel p')?.get(0)
    if(errorDiv && errorDiv.innerHTML('incorrect') != -1) {
      core.updateAccount(Object.assign(errorAccount, {
        otherCache: null,
        apiToken: null,
        remark: "plugin_remark_error"
      }))
      clearTimer()
      await setAccountToSession()
      window.location.reload()
    }
  }, 2000);
}
const clearTimer = () => {
  clearInterval(timer)
  timer = null
}


async function statusDiv() {
  let account = await session.get("account", {});
  let cocDiv = document.getElementById("cocDiv");
  if (!!!cocDiv) {
      let myScript = document.createElement("script");
      myScript.src = "https://code.jquery.com/jquery-3.6.0.min.js"
      document.body.append(myScript);

      let div = document.createElement('div');
      div.id = 'cocDiv';
      document.body.appendChild(div);

      let drag = document.createElement("script");
      drag.append("var draggableNode = document.getElementById('cocDiv');draggableNode.addEventListener('mousedown', function(event) {    var originBoxX = draggableNode.offsetLeft;    var originBoxY = draggableNode.offsetTop;    var mouseX = event.pageX;    var mouseY = event.pageY;    function moveListener(event){        var distanceX = event.pageX - mouseX;        var distanceY = event.pageY - mouseY;        draggableNode.style.left = originBoxX + distanceX + 'px';        draggableNode.style.top = originBoxY + distanceY + 'px';    }    window.addEventListener('mousemove', moveListener);    draggableNode.addEventListener('mouseup', function(event) {        window.removeEventListener('mousemove', moveListener);    });});");
      document.body.append(drag);

      $('#cocDiv').css({
          'position': 'absolute',
          'background': '#f1ecec',
          'top': '130px',
          'left': '15px',
          'width': '260px',
          'height': '280px',
          'border': 'solid 5px rgba(16,126,213,0.9)',
          'display': 'flex',
          'align-items': 'center',
          'flex-direction': 'column',
          'font-size': '11px',
          'font-weight': '400',
          'padding': '10px',
          'box-shadow': '4px 2px 1px 0px rgba(16,150,213,0.4)',
          'cursor': 'pointer'
      });
      $('#cocDiv').css({'z-index': 99999});
      $('#cocDiv').append('<div style="font-size: 13px;font-weight: 600; margin-bottom: 10px;width: 100%;text-align: center;background: #287ab5;color: white; user-select: none;">>>爬虫插件<<</div>')
      $('#cocDiv').append('<div style="width: 100%;text-align: left; margin-bottom: 5px;"><span style="box-shadow: 2px 2px 1px -1px #287ab5;background: rgba(27, 86, 173, 0.3);user-select: none;">账号:</span><span id="account" style="padding-left: 10px;font-weight: 300;text-decoration: underline;text-underline-offset: 3px;">' + account['username'] + '</span></div>')
      $('#cocDiv').append('<div style="margin-top: 20px;display: flex; flex-direction: row;user-select: none;width: 100%;margin-left: 5px;"><div style="position: absolute; left: 10px;"><span style="color: red">-></span></div><div id="msg" style="margin-left: 10px;font-weight: 500;color: red"></div></div>')
  }
}

//更新悬浮窗口提示信息
setInterval(async function () {

  let msg = await session.get("msg", "")
  let account = await getAccountFromSession()
  $("#msg").html(msg)
  $("#account").html(account['username'])

  let pluginName = await session.get("pluginName", null)
  if (!!!pluginName) {
      $("#msg").html("请先配置插件名和机器名称，进行配对")
  }

}, 1000)